package com.draven.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.draven.common.BusinessException;
import com.draven.entity.FileCategory;
import com.draven.entity.FileInfo;
import com.draven.mapper.FileCategoryMapper;
import com.draven.mapper.FileInfoMapper;
import com.draven.service.FileCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文件分类服务实现类
 */
@Slf4j
@Service
public class FileCategoryServiceImpl implements FileCategoryService {

    @Autowired
    private FileCategoryMapper fileCategoryMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    public List<FileCategory> getCategoriesByUserId(Long userId) {
        LambdaQueryWrapper<FileCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileCategory::getUserId, userId)
                .orderByAsc(FileCategory::getSort)
                .orderByDesc(FileCategory::getCreateTime);
        return fileCategoryMapper.selectList(queryWrapper);
    }

    @Override
    public FileCategory addCategory(FileCategory fileCategory) {
        // 检查同名分类
        LambdaQueryWrapper<FileCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileCategory::getUserId, fileCategory.getUserId())
                .eq(FileCategory::getName, fileCategory.getName());
        if (fileCategoryMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "分类名称已存在");
        }

        fileCategoryMapper.insert(fileCategory);
        return fileCategory;
    }

    @Override
    public boolean updateCategory(FileCategory fileCategory) {
        // 检查分类是否存在
        FileCategory existCategory = fileCategoryMapper.selectById(fileCategory.getId());
        if (existCategory == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查权限
        if (!existCategory.getUserId().equals(fileCategory.getUserId())) {
            throw new BusinessException(403, "无权限修改此分类");
        }

        // 检查同名分类
        LambdaQueryWrapper<FileCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileCategory::getUserId, fileCategory.getUserId())
                .eq(FileCategory::getName, fileCategory.getName())
                .ne(FileCategory::getId, fileCategory.getId());
        if (fileCategoryMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "分类名称已存在");
        }

        int result = fileCategoryMapper.updateById(fileCategory);
        
        // 更新关联文件的分类名称
        if (result > 0) {
            LambdaUpdateWrapper<FileInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(FileInfo::getCategoryId, fileCategory.getId())
                    .set(FileInfo::getCategoryName, fileCategory.getName());
            fileInfoMapper.update(null, updateWrapper);
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(Long id, Long userId) {
        // 检查分类是否存在
        FileCategory existCategory = fileCategoryMapper.selectById(id);
        if (existCategory == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查权限
        if (!existCategory.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权限删除此分类");
        }

        // 检查是否有文件使用此分类
        LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileInfo::getCategoryId, id);
        if (fileInfoMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "分类下存在文件，无法删除");
        }

        int result = fileCategoryMapper.deleteById(id);
        return result > 0;
    }

    @Override
    public FileCategory getCategoryById(Long id) {
        return fileCategoryMapper.selectById(id);
    }
} 